package cn.dida.weixin.qyh;

import java.io.File;
import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * 微信企业号操作部门和用户
 * @author weiwei
 */
public class QyhApiClient {
    protected Log logger = LogFactory.getLog(getClass());
    private String api_domain = "https://qyapi.weixin.qq.com";
    private String corpid;
    private String corpsecret;
    private String accessToken;

    public QyhApiClient(String corpid, String corpsecret) {
        this.corpid = corpid;
        this.corpsecret = corpsecret;
        JSONObject accessTokenRe = get("/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret);
        this.accessToken = accessTokenRe == null ? "" : accessTokenRe.getString("access_token");
        logger.info("Ready! access_token : " + accessToken);
    }

    public boolean isReady() {
        return StringUtils.isNotEmpty(accessToken);
    }


    public JSONObject createUser(String userid, String name, Integer departmentId, String mobile) {
        JSONObject postObj = new JSONObject();
        postObj.put("userid", userid);
        postObj.put("name", name);
        postObj.put("department", new Integer[]{departmentId});
        postObj.put("mobile", mobile);
        StringEntity entity = new StringEntity(postObj.toJSONString(), ContentType.APPLICATION_JSON);
        return post("/cgi-bin/user/create?access_token=" + accessToken, entity);
    }

    public JSONObject updateUser(String userid, String name, Integer departmentId, String mobile) {
        JSONObject postObj = new JSONObject();
        postObj.put("userid", userid);
        postObj.put("name", name);
        postObj.put("department", new Integer[]{departmentId});
        postObj.put("mobile", mobile);
        HttpEntity entity = new StringEntity(postObj.toJSONString(), ContentType.APPLICATION_JSON);
        return post("/cgi-bin/user/update?access_token=" + accessToken, entity);
    }

    public JSONObject deleteUser(String userid) {
        return post("/cgi-bin/user/delete?access_token=" + accessToken + "&userid=" + userid, (JSONObject) null);
    }

    public JSONObject getDepartmentList(Integer departmentId) {
        String id = departmentId == null ? "" : departmentId.toString();
        return get("/cgi-bin/department/list?access_token=" + accessToken + "&id=" + id);
    }

    public JSONObject createDepartment(Integer parentId, String name) {
        JSONObject postObj = new JSONObject();
        postObj.put("name", name);
        postObj.put("parentid", parentId);
        return post("/cgi-bin/department/create?access_token=" + accessToken, postObj);
    }

    public JSONObject updateDepartment(Integer id, Integer parentId, String name) {
        JSONObject postObj = new JSONObject();
        postObj.put("id", id);
        postObj.put("name", name);
        postObj.put("parentid", parentId);
        return post("/cgi-bin/department/update?access_token=" + accessToken, postObj);
    }

    public JSONObject deleteDepartment(Integer id) {
        return post("/cgi-bin/department/delete?access_token=" + accessToken + "&id=" + id, (HttpEntity) null);
    }

    public JSONObject uploadMedia(File file, String type) {
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        entityBuilder.addBinaryBody("media", file);
        HttpEntity entity = entityBuilder.build();
        return post("/cgi-bin/media/upload?access_token=" + accessToken + "&type=" + type, entity);
    }

    public JSONObject syncUser(String mediaId) {
        JSONObject postObj = new JSONObject();
        postObj.put("media_id", mediaId);
        return post("/cgi-bin/batch/syncuser?access_token=" + accessToken, postObj);
    }


    public static void main(String[] args) {
        QyhApiClient qyDevSdk = new QyhApiClient("wxf16e8b4d9bbc864a", "YG2njCABUMI0KjLCzpeCR-dCohp51035_ORqcRXDW39z55DDjeIilKgnqxWsxOx_");
        System.out.println(qyDevSdk.getDepartmentList(null));
    }


    private JSONObject get(String uri) {
        JSONObject reobj = null;
        CloseableHttpClient client = HttpClientBuilder.create().build();
        try {
            HttpGet get = new HttpGet(api_domain + uri);
            CloseableHttpResponse re = client.execute(get);
            reobj = JSONObject.parseObject(EntityUtils.toString(re.getEntity()));
        } catch (Exception e) {
            logger.error(e);
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
        return reobj;
    }

    private JSONObject post(String uri, HttpEntity entity) {
        JSONObject reobj = null;
        CloseableHttpClient client = HttpClientBuilder.create().build();
        try {
            HttpPost post = new HttpPost(api_domain + uri);
            post.setEntity(entity);
            CloseableHttpResponse re = client.execute(post);
            reobj = JSONObject.parseObject(EntityUtils.toString(re.getEntity()));
        } catch (Exception e) {
            logger.error(e);
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
        return reobj;
    }

    private JSONObject post(String uri, JSONObject jsonObject) {
        HttpEntity entity = null;
        if (jsonObject != null) {
            entity = new StringEntity(jsonObject.toJSONString(), ContentType.APPLICATION_JSON);
        }
        return post(uri, entity);
    }
}
